import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { isMobileDevice, getRedirectPath } from '@/utils/device'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { requiresGuest: true }
    },
    {
      path: '/mobile/login',
      name: 'mobile-login',
      component: () => import('../views/LoginView.vue'),
      meta: { requiresGuest: true, isMobile: true }
    },
    {
      path: '/',
      redirect: '/dashboard'
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: () => import('../views/DashboardView.vue'),
      meta: { requiresAuth: true }
    },

    {
      path: '/work-orders',
      name: 'work-orders',
      component: () => import('../views/WorkOrdersView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/work-orders/create',
      name: 'work-order-create',
      component: () => import('../views/WorkOrderCreateView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/work-orders/pending',
      name: 'work-order-pending',
      component: () => import('../views/WorkOrderPendingView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/work-orders/completed',
      name: 'work-order-completed',
      component: () => import('../views/WorkOrderCompletedView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/work-orders/reports',
      name: 'work-order-reports',
      component: () => import('../views/WorkOrderReportsView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/work-orders/:id',
      name: 'work-order-detail',
      component: () => import('../views/WorkOrderDetailView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/work-orders/:id/edit',
      name: 'work-order-edit',
      component: () => import('../views/WorkOrderEditView.vue'),
      meta: { requiresAuth: true }
    },

    {
      path: '/work-order-config',
      name: 'work-order-config',
      component: () => import('../views/WorkOrderConfigView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/style-test',
      name: 'style-test',
      component: () => import('../views/StyleTestView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/users',
      name: 'users',
      component: () => import('../views/UserManagementView.vue'),
      meta: { requiresAuth: true, requiresRole: ['admin'] }
    },
    {
      path: '/areas',
      name: 'areas',
      component: () => import('../views/AreaManagementView.vue'),
      meta: { requiresAuth: true, requiresRole: ['admin'] }
    },
    {
      path: '/inventory/materials',
      name: 'inventory-materials',
      component: () => import('../views/InventoryMaterialsView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/inventory/usage',
      name: 'inventory-usage',
      component: () => import('../views/InventoryUsageView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/system/permissions',
      name: 'permissions',
      component: () => import('../views/PermissionManagementView.vue'),
      meta: { requiresAuth: true, requiresRole: ['admin'] }
    },
    {
      path: '/system/config',
      name: 'system-config',
      component: () => import('../views/SystemConfigView.vue'),
      meta: { requiresAuth: true, requiresRole: ['admin'] }
    },
    {
      path: '/system/material-categories',
      name: 'material-categories',
      component: () => import('../views/MaterialCategoryView.vue'),
      meta: { requiresAuth: true, requiresRole: ['admin'] }
    },
    {
      path: '/system/form-templates',
      name: 'form-templates',
      component: () => import('../views/FormTemplateView.vue'),
      meta: { requiresAuth: true, requiresRole: ['admin'] }
    },
    {
      path: '/mobile/maintenance',
      name: 'mobile-maintenance',
      component: () => import('../views/MobileMaintenanceView.vue'),
      meta: { requiresAuth: true, isMobile: true }
    },
    {
      path: '/mobile/work-orders/:id',
      name: 'mobile-work-order-detail',
      component: () => import('../views/MobileWorkOrderDetailView.vue'),
      meta: { requiresAuth: true, isMobile: true }
    },
    {
      path: '/mobile/work-orders/:id/edit',
      name: 'mobile-work-order-edit',
      component: () => import('../views/MobileWorkOrderEditView.vue'),
      meta: { requiresAuth: true, isMobile: true }
    },
    {
      path: '/device-test',
      name: 'device-test',
      component: () => import('../views/DeviceTestView.vue'),
      meta: { requiresAuth: true }
    }
  ],
})



// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 初始化用户信息
  if (authStore.token && !authStore.user) {
    try {
      await authStore.initUser()
    } catch (error) {
      // 如果初始化失败，清除token并跳转到登录页
      authStore.logout()
      if (to.path !== '/login') {
        next('/login')
        return
      }
    }
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    next('/login')
    return
  }

  // 检查是否需要游客状态（如登录页）
  if (to.meta.requiresGuest && authStore.isLoggedIn) {
    // 根据设备类型和用户角色智能跳转
    const isMobile = isMobileDevice()
    const userRole = authStore.user?.role || 'user'
    const redirectPath = getRedirectPath(userRole, isMobile)
    next(redirectPath)
    return
  }

  // 检查角色权限
  if (to.meta.requiresRole && authStore.user) {
    const requiredRoles = to.meta.requiresRole as string[]
    if (!requiredRoles.includes(authStore.user.role)) {
      // 权限不足时也根据设备类型智能跳转
      const isMobile = isMobileDevice()
      const userRole = authStore.user.role
      const redirectPath = getRedirectPath(userRole, isMobile)
      next(redirectPath)
      return
    }
  }

  // 根路径重定向逻辑优化
  if (to.path === '/' && authStore.isLoggedIn && authStore.user) {
    const isMobile = isMobileDevice()
    const userRole = authStore.user.role
    const redirectPath = getRedirectPath(userRole, isMobile)
    next(redirectPath)
    return
  }

  next()
})

export default router
